﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web.Mvc;
using Yyyg.Models;
using Yyyg.WebUI.Models;
using Yyyg.IBLL;
using Yyyg.BLL;

namespace Yyyg.WebUI.Controllers
{
    public class HomeController : Controller
    {
        string rootdir = ConfigurationManager.AppSettings["GoodImageRootDir"];

        public LuckyEntities db { get; set; }

        public IMemberService users { get; set; }

        //主页
        public ActionResult Index()
        {
            //获取最热商品

            HomeIndexVM vm = new HomeIndexVM();

            //获取最热商品列表
            var hots = db.Rushby_now.OrderByDescending(s => s.Rushby_all.All_told - s.Rushby_all.Rem)
                .Take(8)
                .ToArray()
                .Select(s => new GoodItemVM()
                {
                    Info = s.Rushby_all.Goods,
                    MainUrl = s.Rushby_all.Goods.GetMainImgPath(),
                    Rushinfo = s.Rushby_all
                }).ToList();
            vm.HotGoods = hots;

            //获取最热商品列表
            var news = db.Rushby_now.OrderByDescending(s => s.Rushby_all.Createtime)
                .Take(10)
                .ToArray()
                .Select(s => new GoodItemVM()
                {
                    Info = s.Rushby_all.Goods,
                    MainUrl = s.Rushby_all.Goods.GetMainImgPath(),
                    Rushinfo = s.Rushby_all
                }).ToList();
            vm.NewGoods = news;

            //获取即将揭晓集
            var sons = db.Rushby_now.OrderBy(s => s.Rushby_all.Rem)
                .Take(10)
                .ToArray()
                .Select(s => new GoodItemVM()
                {
                    Info = s.Rushby_all.Goods,
                    MainUrl = s.Rushby_all.Goods.GetMainImgPath(),
                    Rushinfo = s.Rushby_all
                }).ToList();
            vm.SoonAnnouns = sons;

            //获取最新揭晓列表
            var njx = db.Rushby_over.OrderByDescending(s => s.Createtime).Take(15);
            var njxlist = new List<LatestAnnounVM>();
            foreach (var s in njx)
            {
                njxlist.Add(new LatestAnnounVM()
                {
                    ByCount = s.Bycount,
                    LottNum = s.Lott_num.ToString(),
                    GdInfo = s.Rushby_all.Goods,
                    PerNum = s.Rushby_all.Per_num.ToString(),
                    UserInfo = s.Member,
                    MainUrl = s.Rushby_all.Goods.GetMainImgPath(),
                    Date = s.Createtime,
                    RushID=s.Rush_id
                });
            }
            vm.NewAnnouns = njxlist;

            var uid = HttpContext.GetUserID();
            ViewBag.ShowMask = false;
            if (uid > 0) ViewBag.ShowMask = users.HasNotViewed(uid);
            return View(vm);
        }

        //商品详情
        public ActionResult GoodAbout(int rhid)
        {

            var res = db.Rushby_all.FirstOrDefault(s => s.Id == rhid);
            if (res == null)
            {
                return HttpNotFound("未找到指定商品!");
            }
            //如果商品已开奖则跳转至开奖页
            if (res.Status == 1)
            {
                return RedirectToAction("PrizeAbout", new { rhid });
            }
            //赋值必要数据
            GoodAboutVM info = new GoodAboutVM();
            info.Info = res.Goods;
            info.GoodType = GoodType.GetByTypeId(res.Goods.Typeid);
            info.Rushinfo = res;
            info.DetUrls = res.Goods.GetDetImgsPath();
            info.SubUrls = res.Goods.GetSubImgsPath();
            info.MainUrl = res.Goods.GetMainImgPath();
            info.Earliers = db.Rushby_over.Where(w => w.Rushby_all.Goods.Gid == res.Gid).OrderByDescending(o => o.Createtime).ToList();

            //查询该夺宝项的夺宝记录
            var rs = db.Orders.Where(w => w.Rush_id == rhid).OrderByDescending(o => o.Createtime).ToArray();
            info.ByTimeLine = rs.GroupBy(g => g.Createtime.ToString("yyyy年MM月dd日"))
                .Select(g => new GoodInfoBaseVM.TimeLineItem()
                {
                    Orders = g.ToList(),
                    Time = g.Key
                }).ToList();
            return View(info);
        }

        //开奖详情
        public ActionResult PrizeAbout(int rhid = -1)
        {

            var res = db.Rushby_all.FirstOrDefault(s => s.Id == rhid);
            if (res == null) return HttpNotFound("未找到指定商品!");
            //如果未开奖则跳转至详情页
            if (res.Status == 0) return RedirectToAction("GoodAbout", new { rhid });

            //拿到开奖数据
            int uid = HttpContext.GetUserID();
            var lott = db.Rushby_over.First(f => f.Rush_id == rhid);
            var last50 = db.Orders.Where(w => w.Createtime < lott.Createtime).OrderByDescending(o => o.Createtime).Take(50).ToArray();
            //显示加载用户信息
            foreach (var item in last50)
            {
                db.Entry(item).Reference(o => o.Member).Load();
                db.Entry(item).Reference(o => o.Rushby_all).Load();
                db.Entry(item.Rushby_all).Reference(o => o.Goods).Load();
            }
            //赋值必要数据
            var vm = new PrizeAboutVM()
            {
                RushInfo = res,
                GoodInfo = res.Goods,
                NewRush = db.Rushby_now.First(w => w.Gid == res.Goods.Gid).Rushby_all,
                LastOrders = last50,
                LottInfo = lott,
                WinUser = lott.Member,
                Info = res.Goods,
                GoodType = GoodType.GetByTypeId(res.Goods.Typeid),
                MainUrl = res.Goods.GetMainImgPath(),
                SubUrls = res.Goods.GetSubImgsPath(),
                Earliers = db.Rushby_over.Where(w => w.Rushby_all.Goods.Gid == res.Gid).OrderByDescending(o => o.Rushby_all.Per_num).ToList()
            };
            //查询该夺宝项的夺宝记录
            var rs = db.Orders.Where(w => w.Rush_id == rhid).OrderByDescending(o => o.Createtime).ToArray();
            //获取时间线
            vm.ByTimeLine = rs.GroupBy(g => g.Createtime.ToString("yyyy年MM月dd日"))
                .Select(g => new GoodInfoBaseVM.TimeLineItem()
                {
                    Orders = g.ToList(),
                    Time = g.Key
                }).ToList();
            return View(vm);
        }

        //商品分类查询结果
        public ActionResult ForType(int t)
        {
            bool isParentType = false;
            Goods_type ptype; //父类
            Goods_type stype; //子类
            List<Goods_type> stypes;//父类下的所有子类

            var type = db.Goods_type.FirstOrDefault(g => g.Typeid == t);
            if (type == null) throw new Exception("未找到指定商品类别!");
            isParentType = type.Parentid < 0;
            stype = type;

            if (isParentType) ptype = type;
            else ptype = db.Goods_type.FirstOrDefault(g => g.Typeid == type.Parentid);

            stypes = db.Goods_type.Where(g => g.Parentid == ptype.Typeid).ToList();
            //在头部添加一个全部标签,如果没有指定子类，则默认为全部
            stypes.Insert(0, new Goods_type() { Typeid = ptype.Typeid, Typename = "全部" });
            IQueryable<Rushby_now> qlist;
            if (isParentType) qlist = db.Rushby_now.Where(w => w.Rushby_all.Goods.Goods_type.Parentid == type.Typeid);
            else qlist = db.Rushby_now.Where(w => w.Rushby_all.Goods.Goods_type.Typeid == type.Typeid);

            var list = new List<GoodItemVM>();
            foreach (var r in qlist)
            {
                var v = new GoodItemVM();
                v.Info = r.Rushby_all.Goods;
                v.MainUrl = v.Info.GetMainImgPath();
                v.Rushinfo = r.Rushby_all;
                list.Add(v);
            }
            ViewBag.QList = list;
            ViewBag.ParentType = ptype;
            ViewBag.SubType = stype;
            ViewBag.SubTypes = stypes;
            return View();
        }

        //搜索结果页
        public ActionResult Search(string q)
        {
            var vm = new SearchResultVM();
            vm.KeyWord = q;
            if (string.IsNullOrEmpty(q)) return View(vm);
            var res = db.Rushby_now.Select(s => s.Rushby_all).Where(w => w.Goods.Title.Contains(q) || w.Goods.Goods_type.Typename.Contains(q)).ToArray();
            vm.Result = res;
            return View(vm);
        }

        //最新揭晓
        public ActionResult Newjx()
        {
            var mod = new NewJxVM();
            mod.HotList = db.Rushby_all.Where(w => w.Status == 0).Take(7).OrderByDescending(o => (o.All_told - o.Rem)).ToList();
            mod.NewBys = db.Orders.Where(o => o.Rushby_all.Status == 0).Take(14).OrderByDescending(o => o.Createtime).ToList();
            //mod.OverList = db.Rushby_over.OrderByDescending(o => o.Createtime).QueryPage(1, 10, out dnums).ToList();
            mod.DataNumbers = db.Rushby_over.Count();
            return View(mod);
        }

        //[OutputCache(Location = System.Web.UI.OutputCacheLocation.Client,Duration =30)]
        public ActionResult NewJxQueryPage(int pindex, int psize)
        {
            int n;
            var list = db.Rushby_over.OrderByDescending(o => o.Createtime).QueryPage(pindex, psize, out n).ToList();
            return View("_PartialNjxItems",list) ;
        }

        //帮助中心
        public ActionResult Helper()
        {
            return View();
        }
    }
}